package io.hellsinger.vortex.data

import io.hellsinger.filesystem.directory.DirectoryEntry
import io.hellsinger.filesystem.directory.DirectoryWalker
import io.hellsinger.filesystem.directory.DirectoryWalker.Companion.CONTINUE
import io.hellsinger.filesystem.directory.DirectoryWalker.Companion.SKIP
import io.hellsinger.filesystem.linux.LinuxOperationOptions
import io.hellsinger.filesystem.linux.directory.LinuxDirectory
import io.hellsinger.filesystem.linux.path.LinuxPath
import io.hellsinger.filesystem.path.EmptyPath
import io.hellsinger.filesystem.path.Path
import kotlinx.coroutines.flow.Flow
import java.io.File

fun parsePath(
    scheme: Int = LinuxOperationOptions.SCHEME,
    path: ByteArray,
): Path {
    if (path.isEmpty()) return EmptyPath()

    return when (scheme) {
        LinuxOperationOptions.SCHEME -> LinuxPath(path)
        else -> throw IllegalArgumentException("Unsupported scheme $scheme")
    }
}

fun File.asPath(scheme: Int = LinuxOperationOptions.SCHEME): Path = absolutePath.asPath(scheme)

fun String.asPath(scheme: Int = LinuxOperationOptions.SCHEME): Path =
    parsePath(
        scheme = scheme,
        path = encodeToByteArray(),
    )

inline fun <P : Path> LinuxDirectory<P>.restrictedTreeWalker(crossinline restrictedChecker: (Path) -> Boolean): Flow<DirectoryEntry<P>> =
    walk(
        object : DirectoryWalker {
            override suspend fun onEntry(path: Path): Int = CONTINUE

            override suspend fun onPostEnterDirectory(path: Path) {}

            override suspend fun onPreEnterDirectory(path: Path): Int =
                if (restrictedChecker(path)) {
                    SKIP
                } else {
                    CONTINUE
                }
        },
    )
